// pages/composite/composite.js
import CanvasDrag from '../../components/canvas-drag/canvas-drag';
let app = getApp();
let rewardedVideoAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ad: true,
    tip: true,
    monster: true,
    cover: true,
    button: true,
    pen: true,
    tab: '1', //图片tab
    active: '',
    src: '',
    left: 0,
    top: 0,
    width: 250, //宽度
    height: 250, //高度
    imageUrl: '',
    graph: {},
    isClear: false,
    operation: "0",
    currentColor: 'black',
    curWidthIndex: 0,
    lineWidthArr: [2, 5, 10, 20],
    avaliableColors: ["black", "red", "blue", "gray", "#ff4081",
      "#009681", "#259b24", "green", "#0000CD", "#1E90FF", "#ADD8E6", "#FAEBD7", "#FFF0F5", // orange
      '#FFEBA3', '#FFDE7A', '#FFCE52', '#FFBB29', '#FFA500', '#D98600', '#B36800', '#8C4D00', '#663500',
      // red
      '#FFAFA3', '#FF887A', '#FF5D52', '#FF3029', '#FF0000', '#D90007', '#B3000C', '#8C000E', '#66000E',
      // green
      '#7BB372', '#58A650', '#389931', '#1A8C16', '#008000', '#005903', '#003303',
      // yellow
      '#FFF27A', '#FFF352', '#FFF829', '#FFFF00', '#D2D900', '#A7B300', '#7E8C00', '#586600',
      // cyan
      '#A3FFF3', '#7AFFF2', '#52FFF3', '#29FFF8', '#00FFFF', '#00D2D9', '#00A7B3', '#007E8C', '#005866',
      // blue
      '#A3AFFF', '#7A88FF', '#525DFF', '#2930FF', '#0000FF', '#0700D9', '#0C00B3', '#0E008C', '#0E0066',
      // Violet
      '#FAB1F7', '#EE82EE', '#C463C7', '#9B48A1', '#73317A', '#4D2154',
      "black"
    ],
    monsters: [

    ],
    images: [{
        name: "怪兽1",
        smallUrl: "http://pic.yupoo.com/denglianchao/8c85d9ce/square.png",
        normalUrl: "http://pic.yupoo.com/denglianchao/8c85d9ce/medium.png",
        sort: 1
      },
      {
        name: "怪兽2",
        smallUrl: "http://pic.yupoo.com/denglianchao/97b1bdc8/square.png",
        normalUrl: "http://pic.yupoo.com/denglianchao/97b1bdc8/small.png",
        sort: 2
      },
      {
        name: "怪兽2",
        smallUrl: "http://pic.yupoo.com/denglianchao/97b1bdc8/square.png",
        normalUrl: "http://pic.yupoo.com/denglianchao/97b1bdc8/small.png",
        sort: 2
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let monsters = wx.getStorageSync('monsters');
    console.log("hhh" + monsters)
    if (monsters && monsters.length > 0) {
      this.setData({
        monsters: monsters,
        images: monsters[0].imgList
      })
    }
    if(wx.createRewardedVideoAd){
      rewardedVideoAd =  wx.createRewardedVideoAd({
        adUnitId: 'adunit-6ce708170398a144'
      })
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      })
      rewardedVideoAd.onClose((res) => {
        console.log('onClose event emit', res)
      })
    }

    rewardedVideoAd.onClose(res => {
      // 用户点击了【关闭广告】按钮
      if (res && res.isEnded) {
         CanvasDrag.savePhoto();
      } else {
        console.log('取消播放')
        // 播放中途退出，不下发游戏奖励
      }
  })
    // this.data.monsters = app.globalData.monsters;
  },
  cropperload(e) {
    console.log("cropper初始化完成");
  },
  loadimage(e) {
    console.log("图片加载完成", e.detail);
    wx.hideLoading();
    //重置图片角度、缩放、位置
    this.cropper.imgReset();
  },
  clickcut(e) {
    console.log(e.detail);
    //点击裁剪框阅览图片
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url] // 需要预览的图片http链接列表
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    CanvasDrag.exportComplex()
      .then((filePath) => {
        console.log('--' + filePath);
        this.data.imageUrl = filePath;
      })
      .catch((e) => {
        console.error(e);
      })
    return {
      title: '我和怪兽有个合影，快来试试吧！',
      path: `/pages/index/index`,
      imageUrl: this.data.imageUrl,
      success: function (res) {
        wx.showToast({
          title: '转发成功',
          icon: 'success',
          duration: 1500
        })
        // 转发成功
      },
      fail: function (res) {
        wx.showToast({
          title: '转发失败',
          icon: 'none',
          duration: 1500
        })
        // 转发失败
      }
    }
  },

  /**
   * 改变背景照片
   */
  onChangeBgImage() {
    CanvasDrag.changeBgImage('/assets/images/test.jpg');
  },
  onAddBgImage(e) {
    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value,
      pen: true,
      tip: false,
      ad: false
    })
    CanvasDrag.addBgImage();
  },
  clearComeBack() {
    CanvasDrag.clearComeBack();
  },
  drawComeBack() {
    CanvasDrag.drawComeBack();
  },
  /**
   * 添加测试图片
   */
  onAddTest(e) {
    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value,
      pen: true
    })
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'image',
        url: '/assets/images/test.png',
      }
    });
  },
  showMonster(e) {
    if (!this.checkPhoto()) {
      wx.showToast({
        title: '请先导入图片',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value,
      pen: true,
      monster: ''
    });
  },
  selectTab(e) {
    let item = e.currentTarget.dataset.item;
    if (item) {
      this.setData({
        tab: item.sort,
        images: item.imgList
      })
    }
  },
  //选择怪物图片
  selectMonster(e) {
    let image = e.currentTarget.dataset.image;
    if (image && image.normalUrl) {
      wx.showLoading({
        title: '图片加载中...'
      })
      let _this = this;
      wx.getImageInfo({
        src: image.normalUrl,
        success(res) {
          wx.hideLoading();
          _this.setData({
            graph: {
              w: 120,
              h: 120,
              type: 'image',
              url: res.path,
            }
          });
        },
        fail() {
          wx.hideLoading();
          wx.showToast({
            title: '加载失败，请联系管理员',
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
  },
  closeMonster(e) {
    this.setData({
      monster: true
    });
  },
  onClear(e) {
    if (!this.checkPhoto()) {
      wx.showToast({
        title: '请先导入图片',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value,
      pen: true,
      button: '', //显示按钮
      operation: '1',
      cover: '' //开启遮罩层
    })
  },
  cancelClear() {
    this.setData({
      operation: '0'
    });
  },
  drawLine(e) {
    if (!this.checkPhoto()) {
      wx.showToast({
        title: '请先导入图片',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value,
      operation: '2',
      button: '',
      pen: ''
    })
  },
  /**
   * 导出图片
   */
  onExport(e) {
    if (!this.checkPhoto()) {
      wx.showToast({
        title: '请先导入图片',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    let value = e.currentTarget.dataset.select;
    this.setData({
      active: value
    })
    CanvasDrag.exportComplex()
      .then((filePath) => {
        console.log(filePath);
        wx.previewImage({
          urls: [filePath]
        })
      })
      .catch((e) => {
        console.error(e);
      })
  },
  savePhoto() {
    if (!this.checkPhoto()) {
      wx.showToast({
        title: '请先导入图片',
        icon: 'none',
        duration: 1500
      })
      return;
    }


    wx.showModal({
      title: '提示',
      content: '观看视频即可保存相册，开发不易，谢谢大家支持！',
      success(res) {
        if (res.confirm) {
          // 用户触发广告后，显示激励视频广告
          if (rewardedVideoAd) {
            rewardedVideoAd.show() .catch(() => {
              // 失败重试
              rewardedVideoAd.load()
                .then(() => rewardedVideoAd.show())
                .catch(err => {
                  console.log('激励视频 广告显示失败')
                })
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 点击设置线条宽度
  clickChangeWidth: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setLineWidthByIndex(index);
  },
  // 设置线条宽度
  setLineWidthByIndex: function (index) {
    let width = this.data.lineWidthArr[index];
    //this.context.setLineWidth(width);
    this.setData({
      curWidthIndex: index
    });
    CanvasDrag.setLineWidth(width);
  },

  // 点击设置线条颜色
  clickChangeColor: function (e) {
    let color = e.currentTarget.dataset.color;
    this.setCurrentColor(color);
  },
  // 设置线条颜色
  setCurrentColor: function (color) {
    this.setData({
      currentColor: color
    });
    CanvasDrag.setCurrentColor(color);
  },
  closeButton(e) {
    if (this.data.operation == '1') {
      this.setData({
        button: true,
        active: '',
        operation: '0',
        pen: true,
        cover: true
      })
    } else if (this.data.operation == '2') {
      this.setData({
        button: true,
        active: '',
        operation: '0',
        pen: true
      })
    }

    CanvasDrag.closeButton();
  },
  saveButton(e) {
    if (this.data.operation == '1') {
      this.setData({
        button: true,
        active: '',
        operation: '0',
        pen: true,
        cover: true
      })
    } else if (this.data.operation == '2') {
      this.setData({
        button: true,
        active: '',
        operation: '0',
        pen: true
      })
    }
    CanvasDrag.saveButton();
  },
  backButton(e) {
    if (this.data.operation == '1') {
      CanvasDrag.clearComeBack();
    } else if (this.data.operation == '2') {
      CanvasDrag.drawComeBack();
    }
  },
  checkPhoto() {
    return CanvasDrag.checkPhoto();
  }
})